#!/usr/bin/env python
#coding=utf-8

import wsgiref.handlers
import logging
import sys
import datetime

sys.path.append('modules')
from base import *
from models import *
from utils import *
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.api import memcache
from BeautifulSoup import BeautifulSoup

class ShowBuyer(BaseRequestHandler):

  def get(self):
		key = cgi.escape(self.request.path[len('/showbuyer/'):])
		if key == '' or key is None:
			key = cgi.escape(self.param('key')).strip()
		buyer = db.get(db.Key(key))
		self.template_values.update({'buyer': buyer})
		self.render('templates/showbuyer.html')
  
class Index(BaseRequestHandler):

  def get(self):

    page = 1
    buyers = []
    totalCount = 0
    
    country = getParamString(self.param('country'))
    if country != '':
      self.redirect('/country/%s' % country)
      return

    category = getParamString(self.param('category'))
    if category != '':
      self.redirect('/category/%s' % category)
      return

    if self.request.path.startswith('/page/'):
      page = int(self.request.path[len('/page/'):])

    totalCount = memcache.get('totalBuyerCount')
    if totalCount is None:
      totalCount = 0

    pager = Pager(page, totalCount, '/page/')
    offset = PAGE_SIZE * (pager.currentPage - 1)
    buyers = Buyer.getLastBuyer(PAGE_SIZE, offset)

    self.template_values.update({'buyers': buyers,
                                 'pager' : pager,
                                 'categories' : memcache.get('categories'),
                                 'now' : format_date(datetime.datetime.utcnow()),
                                 'totalCount': totalCount
                                })
    self.render('templates/index.html')


class ListByCountry(BaseRequestHandler):

  def get(self):

    page = 1
    buyers = []
    totalCount = 0

    path = self.request.path.split('/')
    if len(path) < 3:
      self.redirect('/')
      return

    country = getParamString(path[2])
    if country is None or country == '':
      self.redirect('/')
      return

    if len(path) >= 4:
      page = int(path[3])

    totalCount = memcache.get(country)
    if totalCount is None or totalCount == 0:
      totalCount = Buyer.getBuyerCountByCountry(country)
      memcache.set(country, totalCount)
    
    pager = Pager(page, totalCount, '/country/' + country + '/')

    offset = PAGE_SIZE * (pager.currentPage - 1)
    buyers = Buyer.getBuyerByCountry(country, PAGE_SIZE, offset)

    self.template_values.update({'buyers': buyers,
                                 'country': country,
                                 'pager' : pager,
                                 'categories' : memcache.get('categories'),
                                 'now' : format_date(datetime.datetime.utcnow()),
                                 'totalCount': totalCount
                                })
    self.render('templates/listbycountry.html')


class ListByCategory(BaseRequestHandler):

  def get(self):

    page = 1
    buyers = []
    totalCount = 0

    path = self.request.path.split('/')
    if len(path) < 3:
      self.redirect('/')
      return

    category = getParamString(path[2])
    if category is None or category == '':
      self.redirect('/')
      return

    if len(path) >= 4:
      page = int(path[3])

    totalCount = memcache.get(category)
    if totalCount is None or totalCount == 0:
      totalCount = Buyer.getBuyerCountByCategory(category)
    
    pager = Pager(page, totalCount, '/category/' + category + '/')

    offset = PAGE_SIZE * (pager.currentPage - 1)
    buyers = Buyer.getBuyerByCategory(category, PAGE_SIZE, offset)

    self.template_values.update({'buyers': buyers,
                                 'category': category,
                                 'pager' : pager,
                                 'categories' : memcache.get('categories'),
                                 'now' : format_date(datetime.datetime.utcnow()),
                                 'totalCount': totalCount
                                })
    self.render('templates/listbycategory.html')
  
def main():
  
  url_mapping = [
  		('/', Index),
  		('/page/\\d+', Index),
      ('/category/.*', ListByCategory),
      ('/country/.*', ListByCountry),
  		('/showbuyer/\\w+', ShowBuyer),
			('/showbuyer', ShowBuyer),
			('.*', NotFound)
  		]
  
  application = webapp.WSGIApplication(
  		url_mapping,
  		debug=True)
  wsgiref.handlers.CGIHandler().run(application)
  
if __name__ == "__main__":
  main()